package main

import (
	"fmt"
	"github.com/bitfield/script"
	"log"
	"os"
	"os/exec"
	"strings"
)

const (
	//fabric-network 所在目录
	workdir = "/opt/downloads/test_bootstrap/fabric-samples/test-network/"
	//命令：启动网络
	cmdRunNetwork = "sh network.sh up"
	//命令：关闭网络
	cmdStopNetwork = "sh network.sh down"
	//命令：部署链码
	cmdCleanNetwork = "sh network.sh deployCC"
	//命令：创建通道
	cmdCreateChannelNetwork = "sh network.sh createChannel"
)

func main() {
	//test1()

	//test_exec()
	//exec_with_args()
	//eachLine()
	//test_command()
	//test_shell1()
	//切换到指定工作目录  /opt/downloads/test_bootstrap/fabric-samples/test-network/
	cmd := exec.Command("bash", "-c", cmdRunNetwork)
	execCmd(workdir, cmd)

	cmd = exec.Command("bash", "-c", cmdStopNetwork)
	execCmd(workdir, cmd)
}

func execCmd(dir string, cmd *exec.Cmd) {
	_ = os.Chdir(dir)
	//cmd.Dir = dir // 两种设置路径都可以
	bytes, err := cmd.Output()
	checkErr(err)
	out := string(bytes)
	fmt.Printf("结果：%s", out)
}

/**
命令带参数
*/
func exec_with_args() {
	cmd := exec.Command("java", "--version")
	out, err := cmd.Output()
	if err != nil {
		log.Fatal(err)
	} else {
		fmt.Printf("结果：%s", out)
	}
}

/**
测试执行具体位置下的shell脚本文件，但遇到无法cd到该目录的问题。
有些脚本是必须相对路径执行才能成功的。
解决方案是将本工程与需要被执行的文件放置同一级目录下
*/
func test_shell1() {
	//script.Exec("cd /opt/downloads/test_bootstrap/fabric-samples/test-network/")
	cdErr := os.Chdir(workdir)
	checkErr(cdErr)
	execSh()
	//r, err := script.IfExists("/opt/downloads/test_bootstrap/fabric-samples/test-network/network.sh").
	//	Exec("cd /opt/downloads/test_bootstrap/fabric-samples/test-network/").
	//	Exec("./network.sh up").Stdout()
	//fmt.Println(r)
	//checkErr(err)
}

/**
执行指定位置下的shell文件，正确写法
*/
func execSh() {
	cmd := exec.Command("bash", "-c", cmdRunNetwork)
	cmd.Dir = "/opt/downloads/test_bootstrap/fabric-samples/test-network/" // or whatever directory it's in
	out, err := cmd.Output()
	if err != nil {
		log.Fatal(err)
	} else {
		fmt.Printf("结果：%s", out)
	}
}

func test_command() {
	_, e := script.Exec("java -version").Stdout()
	checkErr(e)
}

/**
遍历读取到的每一行：执行自定义方法
*/
func eachLine() {
	p := script.File("go.mod")
	q := p.EachLine(func(line string, out *strings.Builder) {
		out.WriteString("> " + line + "\n")
	})
	output, err := q.String()
	checkErr(err)
	fmt.Println(output)
}

/**
测试方法执行
*/
func test_exec() {
	// `cat` copies its standard input to its standard output.
	p := script.Echo("hello world").Exec("cat")
	output, err := p.String()
	checkErr(err)
	fmt.Println(output)
	// Output: hello world
}

/**
测试读写文件：提取
*/
func test1() {
	contents, err := script.File("go.mod1").Match("module").AppendFile("result.txt")

	checkErr(err)
	fmt.Println(contents)
}

func checkErr(err error) {
	if err != nil {
		fmt.Println("err:", err)

	}
}
